package com.searchdemo.lucene;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class SearchUtil {

	public static void doSearch(JSONArray datas, String querytext, int n)
			throws IOException, ParseException {
		//Analyzer analyzer = new StandardAnalyzer();
		//实例化IKAnalyzer分词器
		Analyzer analyzer = new IKAnalyzer(true);

		// 将索引存储到内存中
		//Directory directory = new RAMDirectory();
		// 如下想把索引存储到硬盘上，使用下面的代码代替
		Directory directory = FSDirectory.open(new File("./luceneIndex"));

		// 写入索引库
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
		IndexWriter iwriter = new IndexWriter(directory, config);

		for (int i = 0; i < datas.size(); i++) {
			JSONObject obj = datas.getJSONObject(i);
			if (obj != null) {
				Document doc = new Document();
				for (Map.Entry<String, Object> entry : obj.entrySet()) {
					doc.add(new TextField(entry.getKey(),
							"" + entry.getValue(), Field.Store.YES));
				}
				iwriter.addDocument(doc);
			}
		}
		iwriter.close();

		// 读取索引并查询
		DirectoryReader reader = DirectoryReader.open(directory);
		IndexSearcher isearcher = new IndexSearcher(reader);
		// 解析一个简单的查询
		QueryParser parser = new QueryParser("title", analyzer);
		Query query = parser.parse(querytext);
		ScoreDoc[] hits = isearcher.search(query, n).scoreDocs;
		// 迭代输出结果
		for (int i = 0; i < hits.length; i++) {
			Document hitDoc = isearcher.doc(hits[i].doc);
			System.out.println(hitDoc.get("skuno")+"\t"+hitDoc.get("title")+"\t"+hitDoc.get("price")+"\t"+hitDoc.get("detailhref")+"\t"+hits[i].score);
		}
		reader.close();
		directory.close();
	}

}
